﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business.Util;
using ZLCMS.Data.Model;
using NHibernate;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Text;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Business.WeixinService;

namespace ZLCMS.Web.SystemManage.weixin.Senior.Barcode
{
    public partial class BarcodeDetail : System.Web.UI.Page
    {

        public string Ticket { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int uid = 0;
                WxBarcodeInfo barcode = null;
                if (Int32.TryParse(Request["uid"], out uid))
                {
                    using (ISession session = SessionFactoryHelper.CreateSession())
                    {
                        barcode = session.Get<WxBarcodeInfo>(uid);
                    }
                    if (barcode != null)
                    {
                        if (barcode.OwnerAccount == UserKit.GetUserAccountWithoutException())
                        {
                            ViewState["uid"] = uid;
                        }
                    }
                    kind.SelectedValue = barcode.ActionName;
                    seconds.Text = barcode.ExpireSeconds.ToString();
                    sceneId.Text = barcode.SceneId.ToString();
                    memo.Text = barcode.Memo;
                    Ticket = barcode.Ticket;
                }
            }
            else
            {
                WxBarcodeInfo barcode = null;
                int uid = ViewState["uid"] == null ? 0 : (int)ViewState["uid"];
                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    if (uid > 0)
                    {
                        barcode = session.Get<WxBarcodeInfo>(uid);
                    }
                    if (barcode == null)
                    {
                        barcode = new WxBarcodeInfo();
                        barcode.CreateDate = DateTime.Now;
                    }

                    barcode.ActionName = kind.SelectedValue;
                    try
                    {
                        barcode.ExpireSeconds = Int32.Parse(seconds.Text);
                    }
                    catch
                    {
                        barcode.ExpireSeconds = 0;
                    }
                    barcode.SceneId = Int32.Parse(sceneId.Text);
                    barcode.Memo = memo.Text;
                    barcode.OwnerAccount = UserKit.GetUserAccountWithoutException();
                    barcode.Ticket = GetTicket(barcode);
                    session.SaveOrUpdate(barcode);
                    session.Flush();
                }

                FrameHelper _framePage = new FrameHelper(this);
                ReturnCode rc = new ReturnCode()
                {
                    statusCode = 200,
                    message = "操作成功"
                };

                rc.callbackType = "forward";
                rc.forwardUrl = "/SystemManage/weixin/Senior/Barcode/BarcodeDetail.aspx?tabid=BarcodeDetail";

                if (Request["submit_op"] != "1")
                {
                    rc.forwardUrl += "&uid=" + barcode.Id;
                }

                _framePage.Alert(rc);
            }
        }

        protected string GetTicket(WxBarcodeInfo barcode)
        {
            string result = "";

            string posturl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + WeixinUtil.GetAccessToken("admin");
            string jsonStr = string.Format(@"{{
                    ""expire_seconds"": {0}, 
                    ""action_name"": ""{1}"", 
                    ""action_info"": {{
                        ""scene"": {{
                            ""scene_id"": {2}
                        }}
                    }}
                }}", barcode.ExpireSeconds, barcode.ActionName, barcode.SceneId);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(posturl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            byte[] postdata = Encoding.GetEncoding("UTF-8").GetBytes(jsonStr);
            request.ContentLength = postdata.Length;

            Stream newStream = request.GetRequestStream();
            newStream.Write(postdata, 0, postdata.Length);
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
            var reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();//得到结果
            JToken token;
            JObject ticket = JsonConvert.DeserializeObject<JObject>(content);
            if (ticket.TryGetValue("ticket", out token))
            {
                result = token.Value<string>();
            }
            return result;
        }
    }
}